package com.frx.leetoffer.link;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/10/16
 * @Time: 10:40
 */
public class MergeLink {

    public static void main(String[] args){
        Node node = new Node(6);
        Node node1 = new Node(4,node);
        Node node2 = new Node(2,node1);
        Node node3 = new Node(0,node2);
        printLink(node3);
        System.out.println();
        Node otherNode = new Node(5);
        Node otherNode1 = new Node(3,otherNode);
        Node otherNode2 = new Node(1,otherNode1);
        printLink(otherNode2);
        System.out.println();
        Node newNode = mergeLink(node3,otherNode2);
        printLink(newNode);

    }

    public static Node mergeLink(Node head1,Node head2){
        Node node = new Node(0);
        Node cur = node;
        Node n1 = head1;
        Node n2 = head2;
        while (n1!=null && n2!=null){
            if (n1.val < n2.val){
                cur.next = n1;
                n1 = n1.next;
            } else {
                cur.next = n2;
                n2 = n2.next;
            }
            cur = cur.next;
        }
        if (n1 == null){
            cur.next = n2;
        } else {
            cur.next = n1;
        }
        return node.next;
    }

    public static void printLink(Node node){
        System.out.print(node.val);
        node = node.next;
        while (node != null){
            System.out.print(" -> " + node.val);
            node = node.next;
        }
    }

    private static class Node{
        int val;
        Node next;
        public Node(){

        }
        public Node(int val){
            this.val = val;
        }
        public Node(int val,Node next){
            this.val = val;
            this.next = next;
        }
    }
}
